//
//  AppDelegate.swift
//  WeiBoReDo
//
//  Created by 放学跟鸽走 on 2017/4/8.
//  Copyright © 2017年 放学跟鸽走. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
import UserNotifications



@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        //通知类型（这里将声音、消息、提醒角标都给加上）
//        let userSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound],
//                                                      categories: nil)
            //可以添加自定义categories
//        JPUSHService.register(forRemoteNotificationTypes: userSettings.types.rawValue,
//                                  categories: nil)
       
        
        // 启动JPushSDK
//        JPUSHService.setup(withOption: nil, appKey: "0bf2144949ae92a9930392f5",
//                           channel: "Publish Channel", apsForProduction: false)
        window = UIWindow()
        window?.backgroundColor = UIColor.white
        let vc = XMainController()
        window?.rootViewController = vc
        window?.makeKeyAndVisible()
        setupAdditions()
        
        
        DispatchQueue.global().async {
            self.getStatus()
        }
        return true
    }
    
    func getStatus(){
        
        var count = 0
        // 调度组
        let group = DispatchGroup()
        let id = CZSQLiteManager.shared.getMaxSquareNewsId()
        print(id)
        if id > 142643 {
            print("结束")
            return
        }
        sleep(1)
        for i in id...id+250{
            group.enter()
            XNetworkManager.shared.getSingleSquare(id: i, complete: { (json, isSuccess) in
                print("\(count)")
                //
                //获取对应鸽友圈的数据
                guard let news = XSquareRetweetNews.yy_model(with: json ?? [:]),
                    let lng = news.lng,
                    let lat = news.lat,
                    let address = news.address,
                    address != ""
                    else{
                        group.leave()
                        return
                }
                CZSQLiteManager.shared.updateSquareNews(news: news);
                count = count + 1
                let str = "\(i)用户名：\(String(describing: news.tpName))经纬度：(\(lng),\(lat))";
                print(str)
                
                group.leave()
                
            })
        }
        group.notify(queue: .global()) {
            print("完成")
            self.getStatus()
        }
        
    }
    


    func application(_ application: UIApplication,
                     didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        //注册 DeviceToken
//        JPUSHService.registerDeviceToken(deviceToken)
    }
    
    func application(_ application: UIApplication,
                     didReceiveRemoteNotification userInfo: [AnyHashable : Any],
                     fetchCompletionHandler
        completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        //增加IOS 7的支持
//        JPUSHService.handleRemoteNotification(userInfo)
//        completionHandler(UIBackgroundFetchResult.newData)
    }
    
    func application(_ application: UIApplication,
                     didFailToRegisterForRemoteNotificationsWithError error: Error) {
        //可选
        NSLog("did Fail To Register For Remote Notifications With Error: \(error)")
    }

  


}

// MARK: - 设置应用程序额外信息
extension AppDelegate {
    
    fileprivate func setupAdditions() {
        
        // 1. 设置 SVProguressHUD 最小解除时间
        SVProgressHUD.setMinimumDismissTimeInterval(1)
        
        // 2. 设置网络加载指示器
        AFNetworkActivityIndicatorManager.shared().isEnabled = true
        
        // 3. 设置用户授权显示通知
        // #available 是检测设备版本，如果是 10.0 以上
        // Override point for customization after application launch.
        if #available(iOS 10.0, *) {
            let center = UNUserNotificationCenter.current()
            center.requestAuthorization(options: [.alert,.badge,.carPlay,.sound]) { (isSuccess, error) in
                print("授权结果：\(isSuccess ? "成功":"失败")")
            }
        } else {
            let notifySets:UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert,.badge,.sound], categories: nil)
            UIApplication.shared.registerUserNotificationSettings(notifySets)
            // Fallback on earlier versions
        }
    }
}


